<template>
  <cjui-dialog v-model="dialogVisible" width="700" :title="$t(`operate.${dialogAction}`)" @closed="closed">
    <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="left" label-width="6em" class="cjui-g__form is-in-dialog">
      <el-form-item label="文本" prop="input">
        <el-input v-model="formModel.input" style="width: 300px;" />
      </el-form-item>

      <el-form-item label="数值" prop="number">
        <el-input-number v-model="formModel.number" :min="0" />
      </el-form-item>

      <el-form-item label="开关" prop="swicth">
        <el-switch v-model="formModel.swicth" :active-value="0" :inactive-value="1" />
      </el-form-item>

      <el-form-item label="文本域" prop="textarea">
        <el-input v-model="formModel.textarea" type="textarea" :rows="5" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="btnLoading" type="primary" @click="confirm">
        {{ $t('operate.confirm') }}
      </el-button>
      <el-button @click="close">
        {{ $t('operate.cancel') }}
      </el-button>
    </template>
  </cjui-dialog>
</template>

<script lang="ts" setup>
type Action = 'create' | 'edit' | 'detail'

const emits = defineEmits<{
  update: []
}>()

const dialogVisible = ref(false)
const dialogAction = ref<Action>('detail')

const formRef = ref()
const formModel = ref<any>({})
const formRules = {
  input: [
    { required: true, message: '请输入', trigger: 'blur' }
  ],
  number: []
}

const btnLoading = ref(false)
const confirm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate(() => {})
  if (!valid) return
  btnLoading.value = true
  try {
    emits('update')
    close()
  } finally {
    btnLoading.value = false
  }
}

// 弹框操作
const open = (action: Action = 'detail', editData: any = {}) => {
  dialogVisible.value = true
  dialogAction.value = action
  formModel.value = { ...editData }
}
const close = () => {
  dialogVisible.value = false
}
const closed = () => {
  formModel.value = {}
  formRef.value.clearValidate()
}

defineExpose({
  open,
  close
})
</script>
